/*
尽可能还原 Promise 中的每一个 API, 并通过注释的方式描述思路和原理.
*/

/**
 * 模拟实现es6中的promise
 */
// 定义Promise的3个状态：pending fulfilled rejected
const PENDING = 'pending'
const FULFILLED = 'fulfilled'
const REJECTED = 'rejected'
class MyPromise {
  // 实例化时传入执行器executor
  constructor(executor) {
    // 执行executor的过程中捕获Error，如果捕获到就执行reject属性
    try {
      executor(this.resolve, this.reject)
    } catch (e) {
      this.reject(e)
    }
  }

  status = PENDING   // status初始化为pending
  value = undefined
  reason = undefined
  /*将successCallback，failCallback置为数组，能够在多次调用promise时能够保证准确性*/
  successCallback = []
  failCallback = []

  // resolve属性的实现
  resolve = (value) => {
    // 如果status属性不是pending，则终止代码执行
    if (this.status !== PENDING) {
      return
    }
    // 改变promise状态
    this.status = FULFILLED
    this.value = value
    setTimeout(() => {
      while(this.successCallback.length) {
        this.successCallback.shift()()
      }
    })
  }

  reject = (reason) => {
    // 如果status属性不是pending，则终止代码执行
    if (this.status !== PENDING) {
      return
    }
    // 改变promise状态
    this.status = REJECTED
    this.reason = reason
    setTimeout(() => {
      while(this.failCallback.length) {
        this.failCallback.shift()()
      }
    })
  }

  then = (successCallback, failCallback) => {
    // 实现then属性动态传参
    successCallback = successCallback ? successCallback : value => value
    failCallback = failCallback ? failCallback : reason => { throw(reason) }
    // 实现链式调用需要返回新的promise
    let promise2 = new MyPromise((resolve, reject) => {
      // 执行setTimeout将执行器变成异步代码，保证能正常获取promise2
      setTimeout(() => {
        if (this.status === FULFILLED) {
          // 捕获异常
          try {
            let x = successCallback(this.value)
            resolvePromise(promise2, x, resolve, reject)
          } catch (e) {
            reject(e)
          }
        }
        if (this.status === REJECTED) {
          // 捕获异常
          try {
            let x = failCallback(this.reason)
            resolvePromise(promise2, x, resolve, reject)
          } catch (e) {
            reject(e)
          }
        }
        if (this.status === PENDING) {
          // 如果执行器内部存在异步操作，需要将回调函数保存
          this.successCallback.push(() => {
            let x = successCallback(this.value)
            resolvePromise(promise2, x, resolve, reject)
          })
          this.failCallback.push(() => {
            let x = failCallback(this.reason)
            resolvePromise(promise2, x, resolve, reject)
          })
        }
      }, 0)
    })
    return promise2
  }

  catch = (callback) => {
    return this.then(undefined, callback)
  }

  // 实现finally属性，每次执行完then或catch都会去执行finally方法
  finally = (callback) => {
    return this.then((value) => {
      return MyPromise.resolve(callback()).then(() => value)
    }, (reason) => {
      return MyPromise.resolve(callback()).then(() => { throw reason})
    })
  }

  // 实现Promise.all静态方法
  static all = (promiseList) => {
    return new MyPromise((resolve, reject) => {
      const resolveList = []
      let count = 0
      function addData (key, value) {
        resolveList[key] = value
        count++
        // promise执行的过程中存在异步操作，需要在addData方法中当每次执行完promise.then中的函数判断promiseList中所有的promise.then是否都执行完毕
        if (count === promiseList.length) {
          resolve(resolveList)
        }
      }
      for (let i = 0; i < promiseList.length; i++) {
        let current = promiseList[i]
        // 判断current是普通值 还是MyPromise的实例对象
        if (current instanceof MyPromise) {
          current.then((value) => {
            addData(i, value)
          }, (e) => {
            reject(e)
          })
        } else {
          addData(i, current)
        }
      }
    })
  }

  // 实现Promise.resolve静态方法
  static resolve(x) {
    return new MyPromise((resolve, reject) => {
      if (x instanceof MyPromise) {
        return x
      } else {
        return new MyPromise((resolve, reject) => {
          resolve(x)
        })
      }
    })
  }
}

// 解析promise
function resolvePromise(promise2, x, resolve, reject) {
  // 防止promise自身调用的情况, 如果捕获到就调用reject并抛出错误
  if (promise2 === x) {
    return reject(new TypeError('Chaining cycle detected for promise'))
  }
  // 判断promise中then的传参(x)是不是promise，如果是就执行x.then, 不是就执行resolve(x)直接传递给下一个then函数（实现promise的链式调用）
  if (x instanceof MyPromise) {
    x.then(resolve, reject)
  } else {
    resolve(x)
  }
}

module.exports = MyPromise
